#coding:utf-8
import re
from lovewith.share.models import Attachment, AttachServiceType
from lovewith.share.views.modules.attach_flag import AttachFlagApi
from lovewith.share.views.modules.attach_like import AttachLikeApi
from lovewith.share.views.modules.attach_tag import AttachTagApi
from lovewith.share.views.modules.attach_color import AttachColorApi
from lovewith.utils.mtcache import MtCache


class AttachApi:
    def __init__(self):
        pass

    #校验image数据
    @staticmethod
    def check_data(image_id=None):
        if image_id:
            image_id = int(image_id)
            image_data = Attachment.objects.filter(id=image_id, is_delete=False)
            if image_data.exists():
                return image_data[0]

        return None


    #图片总数
    @staticmethod
    def get_total():
        attach_total = MtCache('site_attach_total').get()
        if not attach_total:
            attach_total = Attachment.objects.all().count()
            MtCache('site_attach_total').set(attach_total)

        return attach_total

    #分享所有图片
    @staticmethod
    def get_by_share(share_id):
        return Attachment.objects.filter(share_post_id=int(share_id), is_delete=False).order_by('id')

    #获取封面图片(不包括其它数据)
    @staticmethod
    def get_cover_attach(share_id):
        cover_data = Attachment.objects.filter(share_post_id=int(share_id), is_delete=False, is_cover=1)
        if cover_data.exists():
            cover_data = cover_data[0]
            tag_data = AttachTagApi.get_by_image(cover_data.id)

            #sale
            sale_data = AttachFlagApi.get_goods_by_image(cover_data.id)
            return {'cover': cover_data, 'tag': tag_data, 'sale_data': sale_data}
        else:
            return False

    #单个帖子图片总数
    def get_total_by_share(self, share_id):
        return Attachment.objects.filter(share_post_id=int(share_id), is_delete=False).order_by('id').count()

    #获取帖子所有图片的喜欢
    def get_total_like(self, share_id, user_id):
        like_total = 0
        image_data = self.get_by_share(share_id)
        for img in image_data:
            like_num = AttachLikeApi.get_total_by_image(img.id, user_id)
            like_total += like_num

        return like_total

    #获取图片颜色
    @staticmethod
    def get_attach_color(image_id):
        result = []
        color_data = AttachColorApi.get_by_image(image_id)
        for color in color_data.iterator():
            result.append({
                'id': color.id,
                'name': color.color.name,
                'value': color.color.value,
                'color_id': color.color.id
            })

        return result

    #获取封面
    def get_cover_by_share(self, share_id):
        cover_image = {}
        cover_bgcolor = None

        #图片总数
        image_count = self.get_total_by_share(share_id)
        cover_filter_data = Attachment.objects.filter(share_post_id=share_id, is_cover=1)
        if cover_filter_data.exists():
            cover_image = cover_filter_data[0]
        else:
            #未设置时取第一张
            all_image_data = self.get_by_share(share_id)
            if all_image_data:
                cover_image = all_image_data[0]
                #保存
                cover_image.is_cover = 1
                cover_image.save()

        if cover_image:
            #颜色数据
            color_data = AttachColorApi.get_by_image(cover_image.id)

            #淘客数据
            image_sale_data = ''
            sale_data = AttachFlagApi.get_goods_by_image(cover_image.id)
            if sale_data:
                image_sale_data = sale_data[0]

            if len(color_data) > 0:
                cover_bgcolor = color_data[0]['value']

            description = re.compile(r'<[^>]+>', re.S).sub('', cover_image.share_post.content)

            return {
                'title': cover_image.share_post.title,
                'description': '%s...' % description[0:50],
                'uid': cover_image.share_post.user.id,
                'name': cover_image.share_post.user.username,
                'avatar': cover_image.share_post.user.avatar,
                'cover': cover_image.path,
                'background': cover_bgcolor,
                'share_id': cover_image.share_post.id,
                'cover_id': cover_image.id,
                'is_video': cover_image.share_post.is_video,
                'video': cover_image.share_post.video or '',
                'count': image_count,
                'reserve': cover_image.share_post.scheduled_enbale,
                'sale_data': image_sale_data
            }

        #如果帖子没有任何图片，返回帖子信息，以便前台删除
        return {
            'share_id': share_id
        }

    #获取图片相关信息
    def get_ext_data(self, image_id):
        image_data = self.check_data(image_id)
        color_result = []
        tag_result = []
        tk_data = []
        if image_data:
            color_result = AttachColorApi.get_by_image(image_id)
            tag_result = AttachTagApi.get_by_image(image_id)
            tk_data = AttachFlagApi.get_goods_by_image(image_id)

        return {'image': image_data, 'colors': color_result, 'tags': tag_result, 'tks': tk_data}

    #删除图片
    def delete(self, image_id):
        image_data = self.check_data(image_id)
        if image_data:
            #删除颜色
            AttachColorApi.delete_by_image(image_data.id)
            #删除tag
            AttachTagApi.delete_by_image(image_data.id)
            #删除flag
            AttachFlagApi.delete_by_image(image_data.id)
            #删除like
            AttachLikeApi.delete_by_image(image_data.id)

            #标记为删除
            image_data.is_delete = 1
            image_data.is_cover = 0
            image_data.save()

            #如果删除了封面则重新设置一张封面
            if image_data.is_cover:
                all_image_data = self.get_by_share(image_data.share_post.id)
                if all_image_data:
                    cover_image = all_image_data[0]
                    #保存
                    cover_image.is_cover = 1
                    cover_image.save()

    #添加记录
    @staticmethod
    def add(path, is_cover, share_post):
        new_img = Attachment(path=path, is_cover=is_cover, share_post=share_post)
        new_img.save()
        return new_img


    #获取用户前3个帖子的封面图片
    @staticmethod
    def get_new_post_cover_by_user(user_id, count=3):
        cover_data = Attachment.objects.filter(share_post__user_id=int(user_id), is_cover=1).order_by('-id')[0:3]
        return cover_data


    #获取图片服务类型
    @staticmethod
    def get_service_type(image_id):
        return AttachServiceType.objects.filter(post_image_id=int(image_id))


    @staticmethod
    def add_service_type(service_type, image_data):
        new_service_type = []
        for service_data in service_type:
            new_service_type.append(
                AttachServiceType(post_image=image_data, service=service_data)
            )

        if len(new_service_type) > 0:
            AttachServiceType.objects.bulk_create(new_service_type)